package com.catmiw.swt;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.catmiw.wyz.util.DigestUtils;
import com.catmiw.wyz.util.NetUtils;

public class EnglishWordNetLoader implements Runnable{
	private String keyword;
	private String mp3path;
	private NetFileGetter getter;
	private EnglishWordsXmlHandler xmlhandler;
	
	public EnglishWordNetLoader(String keyword,String mp3path,EnglishWordsXmlHandler xmlhandler,NetFileGetter getter){
		this.keyword=keyword.trim();
		this.mp3path=mp3path;
		this.getter=getter;
		this.xmlhandler=xmlhandler;
	}

	public void run() {
		String ww=keyword.replace(" ", "_");
		String html = NetUtils.getResponseFromNet(DialogAddEnglishWordPhrase.ICBA_URL + ww);
		
		Document doc = Jsoup.parse(html);
		if (doc == null || (!doc.title().contains(keyword))){
			getter.afterLoad(false);

			return;
		}

		// 下载mp3
		Elements mp3s = doc.select("a[onmouseover*=resource]");
		if (mp3s != null) {
			String md = DigestUtils.md5Hex(keyword);
			String urlmp3uk = DialogAddEnglishWordPhrase.ICBA_MP3_RESOURCE_UK + md.substring(0, 2) + "/"
					+ md.substring(2, 4) + "/" + md + ".mp3";
			if (!html.contains(urlmp3uk)){
				String md2=DigestUtils.md5Hex(keyword.toLowerCase());
				urlmp3uk = DialogAddEnglishWordPhrase.ICBA_MP3_RESOURCE_UK + md2.substring(0, 2) + "/"
						+ md2.substring(2, 4) + "/" + md2 + ".mp3";
			}

			String urlmp3us = DialogAddEnglishWordPhrase.ICBA_MP3_RESOURCE_US + md.substring(0, 2) + "/"
					+ md.substring(2, 4) + "/" + md + ".mp3";
			if (!html.contains(urlmp3us)){
				String md2=DigestUtils.md5Hex(keyword.toLowerCase());
				urlmp3us = DialogAddEnglishWordPhrase.ICBA_MP3_RESOURCE_US + md2.substring(0, 2) + "/"
						+ md2.substring(2, 4) + "/" + md2 + ".mp3";
			}
			
			String filemp3uk = mp3path + "/英式/"+ keyword + ".mp3";
			String filemp3us = mp3path + "/美式/"+ keyword + ".mp3";

			for (int i = 0; i < mp3s.size(); i++) {
				Element e = mp3s.get(i);
				if (e.attr("onmouseover").contains(urlmp3uk)) {
					new Thread(new EnglishPronunciationDownloader(urlmp3uk,
							filemp3uk, new NetFileGetter() {
								public void afterLoad(boolean success) {
								}
							})).run();
				}
				if (!keyword.equals(keyword.toLowerCase())){
					
				}

				if (e.attr("onmouseover").contains(urlmp3us)) {
					new Thread(new EnglishPronunciationDownloader(urlmp3us,
							filemp3us, new NetFileGetter() {
								public void afterLoad(boolean success) {
								}
							})).run();
				}
			}
		}

		// 词形变化
		Elements prons = doc.select("div.group_prons > div.group_inf >ul >li ");
		
		Word word=new Word();
		word.setId(keyword);

		if (prons != null) {
			for (int i = 0; i < prons.size(); i++) {
				Element e = prons.get(i);
				String n = prons.get(i).ownText();
				String nn = "";
				Elements ee = e.select("a");
				if (ee != null) {
					for (int j = 0; j < ee.size(); j++) {
						nn = nn + ee.get(j).ownText() + " ";
					}
				}
				if (n.startsWith("复数：")) {
					word.setPlural(nn.trim());
				} else if (n.startsWith("过去式：")) {
					word.setPastTense(nn.trim());
				} else if (n.startsWith("过去分词：")) {
					word.setPastParticiple(nn.trim());
				} else if (n.startsWith("现在分词：")) {
					word.setPresentParticiple(nn.trim());
				} else if (n.startsWith("第三人称单数：")) {
					word.setThirdPersonSingular(nn.trim());
				} else if (n.startsWith("比较级：")) {
					word.setComparative(nn.trim());
				} else if (n.startsWith("最高级：")) {
					word.setSuperlative(nn.trim());
				} else if (n.startsWith("派生词：")) {
					word.setDerivatives(nn.trim());
				}
			}
		}

		Elements items = doc.select("div.collins_en_cn");
		
		List<Meaning> meanings=new ArrayList<Meaning>();
		word.setMeanings(meanings);
		
		Meaning m = null;
		if (items != null) {
			Iterator<Element> iterator = items.iterator();
			int count = 1;
			while (iterator.hasNext()) {
				Element ele = iterator.next();

				Element span = ele.select("span.st").first();

				m = new Meaning();
				word.getMeanings().add(m);
				m.setOrder(count++);
				String mt=null;
				m.setPartOfSpeech("");
				
				boolean find = false;
				if (span != null) {
					mt= span.ownText();
					m.setPartOfSpeech(mt);
					for (String st : DialogAddEnglishWordPhrase.PART_OF_SPEECH) {
						if (st.equals(mt)) {
							m.setPartOfSpeech(span.ownText());
							find = true;
							break;
						}
					}
					if (!find) {
						System.out.println("出现未定义的词性："+mt);
					}
				}

				Elements exels = ele.select("ul > li");
				if (exels != null && exels.size() > 0) {
					List<Example> examples = new ArrayList<Example>();
					int examplecount = 0;
					m.setExamples(examples);
					for (int k = 0; k < exels.size(); k++) {
						Elements ep = exels.get(k).select("p");
						if (ep != null && ep.size() >= 2) {
							Example example = new Example();
							examples.add(example);
							String ttx = ep.get(0).html();
							ttx = ttx
									.replace("<span class=\"text_blue\">", " ")
									.replace("</span>", " ");
							ep.get(0).html(ttx);
							example.setEnglish(ep.get(0).ownText());
							example.setChinese(ep.get(1).ownText());
							example.setOrder(++examplecount);

						}
					}
				}
				span = ele.select("span.text_blue").first();
				if (span != null) {
					m.setChinese(span.ownText()==null?"":span.ownText());
				}
				Element div = ele.select("div.caption").first();
				if (div != null) {
					String t = div.html();
					t = t.replace("<b>", "").replace("</b>", "");
					div.html(t);
					m.setEnglish(div.ownText()==null?"":div.ownText());
				}
			}
		} else {

		}
		xmlhandler.storeWord(word);
		
		//
		getter.afterLoad(true);
	}
	
	public static void main(String [] args){
		String md = DigestUtils.md5Hex("japan");
		System.out.println(md);
		md = DigestUtils.md5Hex("Japan");
		System.out.println(md);
	}
}
